package ua.epam.muzalevskiy.traction.commands;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.epam.muzalevskiy.traction.configuretion.MessageConfigurer;
import ua.epam.muzalevskiy.traction.configuretion.PagePathConfigurer;
import ua.epam.muzalevskiy.traction.dao.AdministratorDao;
import ua.epam.muzalevskiy.traction.dao.DaoFactory;
import ua.epam.muzalevskiy.traction.dao.UserDao;
import ua.epam.muzalevskiy.traction.dao.exceptions.NotExistsParameterException;
import ua.epam.muzalevskiy.traction.user.User;

/**
 * <code>LoginCommand</code> class is the <code>Command</code> 
 * interface implementation, that realized <code>Command</code> pattern.
 * Current class encapsulate action of user login in system.
 *
 * @author Muzalevskiy Vitaliy
 * @see Command
 * @see User
 * @see RegisteredUser
 */
public class LoginCommand implements Command {

    private static DaoFactory factory = new DaoFactory();
    private UserDao userDao = factory.getUserDao();
    private AdministratorDao adminDao = factory.getAdministratorDao();
    // defines login and password values from the request
    private static final String PARAM_NAME_LOGIN = "login";
    private static final String PARAM_NAME_PASSWORD = "password";
    private static final String SESSION_ATTRIBUTE_NAME_USER_TYPE = "user_type";
    private static final String SESSION_ATTRIBUTE_NAME_USER_NAME = "user_name";
    
    @Override
    public String execute(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        String page;
        String login = request.getParameter(PARAM_NAME_LOGIN);
        String pass = request.getParameter(PARAM_NAME_PASSWORD);
        User user;
        try {
            try {
                user = adminDao.getAdministrator(login, pass);
            } catch (NotExistsParameterException ex) {
                user = userDao.getUser(login, pass);
            }
            //stores user type in a current session
            request.getSession().setAttribute(SESSION_ATTRIBUTE_NAME_USER_TYPE,
                    user.getUserType());
            request.getSession().setAttribute(SESSION_ATTRIBUTE_NAME_USER_NAME,
                    user.getName());
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.INDEX_PAGE);
        } catch (NotExistsParameterException ex) {
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE,
                    MessageConfigurer.getInstance()
                    .getProperty(MessageConfigurer.LOGIN_ERROR_MESSAGE));
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        }
        return page;
    }
}
